package hotel.client;

import hotel.rmi.HotelService;
import hotel.rmi.to.Guest;
import hotel.rmi.to.Room;

import java.io.PrintStream;
import java.rmi.Naming;
import java.rmi.RemoteException;

public class HotelClient {

	HotelService service;

	HotelClient(String hostname) {
		try {
			service = (HotelService) Naming.lookup("rmi://" + hostname
					+ "/CalculatorService");
		} catch (Exception e) {
			System.out.println("Received Exception:");
			System.out.println(e);
			System.exit(1);
		}
	}

	static void print_info() {
		System.out.println("Usage:");
		System.out.println("  hotelclient list <host>");
		System.out.println("  hotelclient book <host> <type> '<guest name>'");
		System.out.println("  hotelclient guests <host>");
	}

	void printRoom(final PrintStream ps, Room room) {
		String msg = "%1$d rooms of type %2$d at %3$d euros per night\n";
		ps.format(msg, room.getFreeCount(), room.getId(), room.getPrice());

	}

	void list() {
		try {
			for (Room room : service.getAvailableRooms())
				printRoom(System.out, room);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	void book(int type, String name) {
		try {
			service.book(type, name);
			System.out.println("Booked.");
		} catch (RemoteException e) {
			System.out.println(e.getCause().getMessage());
		}
	}

	void guests() {
		int i = 0;
		try {
		for (Guest guest : service.getGuests())
			System.out.println(i++ + ". " + guest.getName());
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		if (args.length == 2 && args[0].equals("list"))
			new HotelClient(args[1]).list();
		else if (args.length == 4 && args[0].equals("book"))
			new HotelClient(args[1]).book(Integer.parseInt(args[2]),
					args[3]);
		else if (args.length == 2 && args[0].equals("guests"))
			new HotelClient(args[1]).guests();
		else
			print_info();
	}
}
